package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.relation.RoleResult;
import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;


    @Transactional
    public void save(Role role, Long[] ids) {
        //除了往role表中插入角色数据
        roleMapper.insert(role);
        //还要往中间表role_permission存入这个角色分配权限数据
        if (ids != null && ids.length > 0) {
            for (Long permissionId : ids) {
                roleMapper.insertRelation(role.getId(), permissionId);
            }

        }

    }

    @Transactional
    public void delete(Long id) {
        //删除中间表中的数据

        roleMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    public void update(Role role, Long[] ids) {
        roleMapper.updateByPrimaryKey(role);
        //先从中间表role_permission删除与角色相关的数据
        roleMapper.deleteRelation(role.getId());


        //再往这张表role_permission插入这个角色新分配的权限数据
        if (ids != null && ids.length > 0) {
            for (Long permissionId : ids) {
                roleMapper.insertRelation(role.getId(), permissionId);
            }

        }

    }

    @Transactional
    public Role get(Long id) {

        return roleMapper.selectByPrimaryKey(id);
    }

    @Transactional
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Transactional
    public PageInfo<Role> query(QueryObject qo) {
        //告诉Mybatis分页插件 设置查询第几页,每页多少条
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> roles = roleMapper.selectForList(qo);
        return new PageInfo<Role>(roles);
    }
}